package com.bestom.multispectrallight;
/**
 * 项目描述：属于安卓蓝牙开发，通过连接蓝牙方式控制灯光的变化。
 * 功能：1，搜索，扫描，显示所扫描到的蓝牙设备，连接蓝牙开始控制灯光
 *      2，调节进度条可改变灯光
 *      3，有停止扫描蓝牙功能
 *      4，可看到某台设备蓝牙是否连接
 *      5，可保存展示灯光进度条位置数据，并且可以进行一次性开
 *      6，可删除保存的记录
 * 实现思路：
 */

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothManager;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bestom.multispectrallight.callback.BTGattCallback;
import com.bestom.multispectrallight.callback.BleListen;
import com.bestom.multispectrallight.callback.ScanCallback;
import com.bestom.multispectrallight.sqlite.MySqlite;
import com.bestom.multispectrallight.util.DataTurn;
import com.bestom.multispectrallight.util.SharedPreferencesUtil;
import com.bestom.multispectrallight.util.ToastUtil;
import com.bestom.multispectrallight.util.WeiboDialogUtils;
import com.suke.widget.SwitchButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import static com.bestom.multispectrallight.callback.ScanCallback.mArrayList;


/**
 * @author shulman
 */
public class MainActivity extends BaseActivity implements BleListen {
    /** 初始化进度条 */
    private SeekBar seek1;
    private SeekBar seek2;
    private SeekBar seek3;
    private SeekBar seek4;
    private SeekBar seek5;
    private SeekBar seek6;
    private SeekBar seek7;
    private SeekBar seek8;
    private SeekBar seek9;
    private SeekBar seek10;
    /** 初始化显示进度条进度数字的编辑框 */
    private EditText edit1;
    private EditText edit2;
    private EditText edit3;
    private EditText edit4;
    private EditText edit5;
    private EditText edit6;
    private EditText edit7;
    private EditText edit8;
    private EditText edit9;
    private EditText edit10;
    /** 滚动布局 */
    private ScrollView scrollView;
    /** 无蓝牙连接的提示TextView */
    private TextView empty;
    /** 保存进度条数据记录的按钮 */
    private Button btnSave;
    /** 可以展示数据记录按钮 */
    private Button btnShow;
    /** 初始化一个int数组来存储每条进度条数据 */
    private int[] data;
    /**
     * 根据进度条变化前后来设置EditText内容，进度条变化前值为false，不让EditText显示，变化后设置为真，显示
     */
    private boolean flag = true;
    /** 权限 */
    private final String[] permissions = {Manifest.permission.ACCESS_COARSE_LOCATION};
    /** 进度条最大值 */
    private final String MAX = "255";
    /** 进度条最小值 */
    private final String MIN = "0";
    /** 权限获取成功的请求码 */
    private final int mRequestCode = 123;
    /**屏幕的宽  屏幕的高*/
    private int width;
    private int height;
    /** 记录保存数据弹出框选中的上一次的位置 */
    int index = 0;
    /** 下拉框 */
    private Spinner spinner;
    /** 是否连接蓝牙的开关 */
    private SwitchButton onOff;
    /** 下拉框适配器 */
    private ArrayAdapter<String> spinnerAdapter;
//    String[] spinnerArr = new String[20];
    /**下拉框保存的数据的集合*/
    ArrayList<String> spinnerArr = new ArrayList<>();
    /**boolean  isAuto
     * 用于判断是点击开关按钮还是下拉框选择
     * true  表示进行下拉框选择改变按钮状态,不做按钮点击逻辑
     * false 表示点击开关按钮改变按钮状态，进行按钮点击逻辑*/
    private boolean isAuto = false;
    MySqlite mySqlite;
    int location=0;
    String[] covertedArray;
    /**  蓝牙gatt集合 */
    public static HashMap<String, BluetoothGatt> gattHashMap=new HashMap<>();
    /**  蓝牙gatt写入信息集合 */
    public static HashMap<String, BluetoothGattCharacteristic> writeHashMap=new HashMap<>();
    /**  蓝牙是否连接集合 */
    public static HashMap<String, Boolean> isConnectMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /** 初始化数据库 */
        mySqlite=new MySqlite(this);


        // 加载视图组件
        initView();
        // 设置组件监听
        initListen();
        // 初始化类及数据
        initData();

    }


    /**
     *  onCreateOptionsMenu(Menu menu) 创建菜单Menu */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        //inflate的作用就是将一个用xml定义的布局文件查找出来
        inflater.inflate(R.menu.main, menu);
        //返回true则显示该menu,false 则不显示;(只会在第一次初始化菜单时调用)
        return true;
    }


    //isFlag根据该值的真假来判断显示搜索按钮还是停止搜索按钮
    boolean isFlag=true;
    //搜索菜单按钮
    MenuItem search;
    //停止菜单按钮
    MenuItem stop;
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        //找到菜单按钮
        search=menu.findItem(R.id.action_search);
        stop = menu.findItem(R.id.action_stop);
        /**
         * isFlag为真时，显示搜索按钮，隐藏停止按钮，反之，则相反
         */
        if(isFlag){
            search.setVisible(true);
            stop.setVisible(false);
        }else{
            search.setVisible(false);
            stop.setVisible(true);
        }

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            /**
             *搜索
             */
            case R.id.action_search:
                mArrayList.clear();
                //权限打开并且扫描·
                    permissionsOk();
                    //设置为假  令搜索按钮消失，停止按钮出现
                    isFlag=false;
                /**
                 * 由于onCreateOptionsMenu只在第一次初始化时运行一次，所以再次更改界面则需要再调用一次
                 */
                    invalidateOptionsMenu();
                    break;
                    //停止扫描
            case R.id.action_stop:
                /**  停止扫描 */
                stopScanDevice();
                /**
                 * 点击停止后令搜索按钮出现
                 */
                isFlag=true;
                popupWindow.dismiss();
                invalidateOptionsMenu();
                break;

        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 加载视图组件方法
     */

    private void initView() {

        scrollView=findViewById(R.id.scroll_view);
        empty = findViewById(R.id.empty);
        onOff = findViewById(R.id.on_off);
        btnSave = findViewById(R.id.btn_save);
        btnShow = findViewById(R.id.btn_show);
        spinner = findViewById(R.id.device_spinner);


        seek1 = findViewById(R.id.seek1);
        seek2 = findViewById(R.id.seek2);
        seek3 = findViewById(R.id.seek3);
        seek4 = findViewById(R.id.seek4);
        seek5 = findViewById(R.id.seek5);
        seek6 = findViewById(R.id.seek6);
        seek7 = findViewById(R.id.seek7);
        seek8 = findViewById(R.id.seek8);
        seek9 = findViewById(R.id.seek9);
        seek10 = findViewById(R.id.seek10);

        edit1 = findViewById(R.id.edit1);
        edit2 = findViewById(R.id.edit2);
        edit3 = findViewById(R.id.edit3);
        edit4 = findViewById(R.id.edit4);
        edit5 = findViewById(R.id.edit5);
        edit6 = findViewById(R.id.edit6);
        edit7 = findViewById(R.id.edit7);
        edit8 = findViewById(R.id.edit8);
        edit9 = findViewById(R.id.edit9);
        edit10 = findViewById(R.id.edit10);


    }
    /** 光谱数据记录弹出框 */
    private AlertDialog alertDialog2;
    /** 光谱数据记录删除弹出框 */
    private AlertDialog alertDialog1;
    //手机上返回键点击事件
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {


            if (keyCode == KeyEvent.KEYCODE_BACK ) {
                //如果返回键按下
                //此处写退向后台的处理
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
                return true;
            }

        return super.onKeyLongPress(keyCode, event);
    }

    /**
     * 设置组件监听方法
     */
    private void initListen() {

        /**
         * 初始化数组data
         */
        data = new int[10];

        seek1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                /**
                 *进度条变动时，输入框数值随着一起改动
                 */
                if (flag) edit1.setText(String.valueOf(progress));
                data[0] = seek1.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });

        edit1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                /** 输入框变化前标志为false */
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit1.setText(MIN);
                    /**
                     * 定义光标显示位置
                     */
                    edit1.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit1.setText(MAX);
                    edit1.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit1.setText(s.toString().substring(1));
                    //光标位置
                    edit1.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek1.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });

        seek2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (flag) edit2.setText(String.valueOf(progress));
                data[1] = seek2.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });
        edit2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit2.setText(MIN);
                    edit2.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit2.setText(MAX);
                    edit2.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit2.setText(s.toString().substring(1));
                    edit2.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek2.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });

        seek3.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (flag) edit3.setText(String.valueOf(progress));
                data[2] = seek3.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });
        edit3.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit3.setText(MIN);
                    edit3.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit3.setText(MAX);
                    edit3.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit3.setText(s.toString().substring(1));
                    edit3.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek3.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });

        seek4.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (flag) edit4.setText(String.valueOf(progress));
                data[3] = seek4.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });
        edit4.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit4.setText(MIN);
                    edit4.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit4.setText(MAX);
                    edit4.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit4.setText(s.toString().substring(1));
                    edit4.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek4.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });

        seek5.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (flag) edit5.setText(String.valueOf(progress));
                data[4] = seek5.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });
        edit5.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit5.setText(MIN);
                    edit5.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit5.setText(MAX);
                    edit5.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit5.setText(s.toString().substring(1));
                    edit5.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek5.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });

        seek6.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (flag) edit6.setText(String.valueOf(progress));
                data[5] = seek6.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });
        edit6.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit6.setText(MIN);
                    edit6.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit6.setText(MAX);
                    edit6.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit6.setText(s.toString().substring(1));
                    edit6.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek6.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });

        seek7.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (flag) edit7.setText(String.valueOf(progress));
                data[6] = seek7.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });
        edit7.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit7.setText(MIN);
                    edit7.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit7.setText(MAX);
                    edit7.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit7.setText(s.toString().substring(1));
                    edit7.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek7.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });

        seek8.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (flag) edit8.setText(String.valueOf(progress));
                data[7] = seek8.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });
        edit8.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit8.setText(MIN);
                    edit8.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit8.setText(MAX);
                    edit8.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit8.setText(s.toString().substring(1));
                    edit8.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek8.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });

        seek9.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (flag) edit9.setText(String.valueOf(progress));
                data[8] = seek9.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });
        edit9.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit9.setText(MIN);
                    edit9.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit9.setText(MAX);
                    edit9.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit9.setText(s.toString().substring(1));
                    edit9.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek9.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });

        seek10.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (flag) edit10.setText(String.valueOf(progress));
                data[9] = seek10.getProgress();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mHandler.sendEmptyMessage(12);
            }
        });
        edit10.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                flag = false;
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().isEmpty()) {
                    edit10.setText(MIN);
                    edit10.setSelection(1);
                } else if (Integer.parseInt(s.toString()) > Integer.parseInt(MAX)) {
                    edit10.setText(MAX);
                    edit10.setSelection(3);
                } else if (s.length() > 1 && s.toString().startsWith(MIN)) {
                    edit10.setText(s.toString().substring(1));
                    edit10.setSelection(1);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                seek10.setProgress(Integer.parseInt(s.toString().isEmpty() ? MIN : s.toString()));
                flag = true;
            }
        });
        /**
         * 保存按钮点击事件
         */
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * StringBuilder：容器，不必考虑线程安全问题
                 */
                StringBuilder value = new StringBuilder();
                /**  令其存为格式：    12,34,35,67,12,23,24,74,57,255  */
                for (int i = 0; i < data.length; i++) {
                    if (i == data.length - 1) {
                        value.append(data[i]);
                    } else {
                        value.append(data[i]).append(",");
                    }
                }
                /**
                 * 保存到数据库当中，key值为name
                 */
                SQLiteDatabase db= mySqlite.getWritableDatabase();
                ContentValues values=new ContentValues();
                values.put("name", String.valueOf(value));
                /**
                 * 把值插入到数据库中
                 */
                db.insert("record", null, values);
                db.close();
                Toast.makeText(getApplicationContext(), "保存记录成功", Toast.LENGTH_SHORT).show();
            }
        });
        /**
         * 开关选中监听事件
         */
        onOff.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isAuto) return;
                if (isChecked){
                    /** 获取当前选中下拉框选中的文字内容  */
                    String spinner_item = spinner.getSelectedItem().toString();
                    /**
                     * 获取当前蓝牙bluetoothGatt
                     */
                    BluetoothGatt bluetoothGatt = gattHashMap.get(spinner_item);
                    //mArrayList.clear();

                    //连接
                    bluetoothGatt.connect();
                    /**
                     * 当前设备连接状态存储为true
                     */
                    isConnectMap.put(spinner_item, true);
                }else {
                    String spinner_item = spinner.getSelectedItem().toString();
                    BluetoothGatt bluetoothGatt = gattHashMap.get(spinner_item);
                    bluetoothGatt.disconnect();
                    mArrayList.clear();
                    isConnectMap.put(spinner_item, false);
                }
            }
        });

        //展示保存记录
        btnShow.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String[] split = SharedPreferencesUtil.getInstance().getValue(spinner.getSelectedItem().toString(),"").toString().split(",");
                System.out.println("spinner.getSelectedItem().toString()"+spinner.getSelectedItem().toString());
                Object locationObject = "0";
                if (split.length == 11){
                    locationObject = split[10];
                }

                location = Integer.parseInt(locationObject.toString());
                /**
                 * 查询数据库，得到数据自增长_id,以"record" + _id形式存入ArraList集合
                 */
                SQLiteDatabase db=mySqlite.getReadableDatabase();
                Cursor cursor=db.rawQuery("select * from record",null);
                if(cursor.getCount()==0){
                    Toast.makeText(MainActivity.this,"当前无记录",Toast.LENGTH_SHORT).show();
                    return;
                }

                ArrayList<String> mArrayList = new ArrayList();
                while(cursor.moveToNext()){
                    int ii=cursor.getInt(cursor.getColumnIndex("_id"));
                    mArrayList.add("record" + ii);

                }
                cursor.close();
                db.close();
                /**
                 * 从集合当中取出存到数组 covertedArray  String[] finalCovertedArray
                 */
                covertedArray = new String[mArrayList.size()];
                    covertedArray = (String[]) mArrayList.toArray(covertedArray);
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
                    alertBuilder.setTitle("保存记录");
                    String[] finalCovertedArray = covertedArray;
                    index= Integer.parseInt(finalCovertedArray[0].substring(6));
                //SharedPreferencesUtil.getInstance().putValue("index", index);


                    alertBuilder.setNeutralButton("删除", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            AlertDialog.Builder alertBuilder1 = new AlertDialog.Builder(MainActivity.this);
                            //设置弹出对话框标题
                            alertBuilder1.setTitle("删除记录");
                            //设置弹出对话框提示信息
                            alertBuilder1.setMessage("您确定要删除此条记录吗？");
                            alertBuilder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int i) {

                                    Object indexObject = SharedPreferencesUtil.getInstance().getValue("index", index);
                                    index = Integer.parseInt(indexObject.toString());
                                    //删除集合中的数据
                                    remove(mArrayList, "record"+index);
                                    //删除数据库中数据
                                    SQLiteDatabase db=mySqlite.getReadableDatabase();
                                    db.delete("record","_id=?",new String[]{String.valueOf(index)});
                                    db.close();
                                    SharedPreferencesUtil.getInstance().putValue("location",i);
                                }
                            });
                            alertBuilder1.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    alertDialog1.dismiss();
                                }
                            });
                            alertDialog1 = alertBuilder1.create();
                            alertDialog1.show();
                        }
                    });


                    alertBuilder.setSingleChoiceItems(covertedArray, location, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            location=i;
                            Toast.makeText(MainActivity.this, finalCovertedArray[i], Toast.LENGTH_SHORT).show();
                            index= Integer.parseInt(finalCovertedArray[i].substring(6));
                            SharedPreferencesUtil.getInstance().putValue("index", index);
                            SharedPreferencesUtil.getInstance().getValue("location", location);

                        }
                    });

                    alertBuilder.setPositiveButton("应用", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int posion) {
                            SQLiteDatabase db=mySqlite.getReadableDatabase();
                            Cursor cursor=db.rawQuery("select * from record where _id=?",new String[]{String.valueOf(index)});
                            cursor.moveToFirst();
                            String  str=cursor.getString(cursor.getColumnIndex("name"));
                            String[] dataarr = str.split(",");
                            seek1.setProgress(Integer.parseInt(dataarr[0]));
                            seek2.setProgress(Integer.parseInt(dataarr[1]));
                            seek3.setProgress(Integer.parseInt(dataarr[2]));
                            seek4.setProgress(Integer.parseInt(dataarr[3]));
                            seek5.setProgress(Integer.parseInt(dataarr[4]));
                            seek6.setProgress(Integer.parseInt(dataarr[5]));
                            seek7.setProgress(Integer.parseInt(dataarr[6]));
                            seek8.setProgress(Integer.parseInt(dataarr[7]));
                            seek9.setProgress(Integer.parseInt(dataarr[8]));
                            seek10.setProgress(Integer.parseInt(dataarr[9]));
                            cursor.close();
                            db.close();

                            SharedPreferencesUtil.getInstance().putValue("location", location);
                            String oldValue = str + "," + location;
                            SharedPreferencesUtil.getInstance().putValue(spinner.getSelectedItem().toString(), oldValue);
                            mHandler.sendEmptyMessage(12);
                            alertDialog2.dismiss();
                        }
                    });

                    alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Object locationObject = SharedPreferencesUtil.getInstance().getValue("location", location);
                            location = Integer.parseInt(locationObject.toString());
                            alertDialog2.dismiss();
                        }
                    });

                    alertDialog2 = alertBuilder.create();
                    alertDialog2.show();

            }
        });
    }
    // 强烈推荐使用Iterator，保证正确
    public static void remove(List<String> list, String target){
        Iterator<String> iter = list.iterator();
        while (iter.hasNext()) {
            String item = iter.next();
            if (item.equals(target)) {
                iter.remove();
            }
        }
    }


    /**
     * 初始化类及数据方法
     */
    private void initData() {
        //创建一个数组适配器
        spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, spinnerArr);
        /**
         *设置下拉列表框的下拉选项样式
         */
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //连接状态
                isAuto = true;
                onOff.setChecked(isConnectMap.get(spinner.getSelectedItem()));
                isAuto = false;

                String value = (String) SharedPreferencesUtil.getInstance().getValue(spinner.getSelectedItem().toString(), "");
                if (!value.isEmpty()){
                    String[] split = value.split(",");
                    seek1.setProgress(Integer.parseInt(split[0]));
                    seek2.setProgress(Integer.parseInt(split[1]));
                    seek3.setProgress(Integer.parseInt(split[2]));
                    seek4.setProgress(Integer.parseInt(split[3]));
                    seek5.setProgress(Integer.parseInt(split[4]));
                    seek6.setProgress(Integer.parseInt(split[5]));
                    seek7.setProgress(Integer.parseInt(split[6]));
                    seek8.setProgress(Integer.parseInt(split[7]));
                    seek9.setProgress(Integer.parseInt(split[8]));
                    seek10.setProgress(Integer.parseInt(split[9]));
                    index = Integer.parseInt(split[10]);
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        mBluetoothAdapter = initBluetoothAdapter();
        scanCallback = new ScanCallback(mBluetoothAdapter, this);
        handler = new Handler();
        mDataTurn = new DataTurn();
        mBleList = new ArrayList<>();
        mBleAdapter = new BleAdapter();
        //获取当前屏幕的宽高
        Window window = getWindow();
        DisplayMetrics metric = new DisplayMetrics();
        window.getWindowManager().getDefaultDisplay().getMetrics(metric);
        // 屏幕宽度（像素）
        width = metric.widthPixels;
        // 屏幕高度（像素）
        height = metric.heightPixels;


    }

    private class BleAdapter extends RecyclerView.Adapter<BleHolder> {

        @NonNull
        @Override
        public BleHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = getLayoutInflater().inflate(R.layout.ble_item, parent, false);
            return new BleHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull BleHolder holder, int position) {
            BluetoothDevice device = mBleList.get(position);
            holder.device = device;

            String name = device.getName() == null ? "unknown" : device.getName();
            holder.text1.setText(name);
            SpannableStringBuilder info = new SpannableStringBuilder();

            info.append("Mac:").append(device.getAddress());
            info.setSpan(new ForegroundColorSpan(0xFF9E9E9E), 0, 21, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            info.setSpan(new ForegroundColorSpan(0xFF8D6E63), 21, info.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            holder.text2.setText(info);
        }

        @Override
        public int getItemCount() {
            return mBleList.size();
        }
    }

    Dialog dialog;

    private class BleHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        BluetoothDevice device;
        TextView text1;
        TextView text2;

        BleHolder(View itemView) {
            super(itemView);

            text1 = itemView.findViewById(android.R.id.text1);
            text2 = itemView.findViewById(android.R.id.text2);
            text2.setTextSize(14);

            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            ThisApplication.getApplication().setBluetoothDevice(device, MainActivity.this);
            popupWindow.dismiss();
            dialog = WeiboDialogUtils.createLoadingDialog(MainActivity.this, "正在连接");

        }
    }

    /**
     * 检测权限
     */
    private void permissionsOk() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            int i = ContextCompat.checkSelfPermission(getApplicationContext(), permissions[0]);
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            if (i != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, permissions, mRequestCode);
            } else scanDevice();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == mRequestCode) {
            boolean isAllGranted = true;
            for (int result : grantResults) {
                if (result == PackageManager.PERMISSION_DENIED) {
                    isAllGranted = false;
                    break;
                }
            }
            //获取权限成功
            if (isAllGranted) scanDevice();
                //如果没有获取权限，那么可以提示用户去设置界面--->应用权限开启权限
            else ToastUtil.toast("Please go to set the interface opening permission");
        }
    }

    /**
     * 获取蓝牙适配器
     */
    private BluetoothAdapter initBluetoothAdapter() {
        BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        return mBluetoothManager.getAdapter();
    }

    /**
     * 检查蓝牙是否打开
     */
    private boolean isAdapterEnabled() {
        return BluetoothAdapter.getDefaultAdapter().isEnabled();
    }

    private BluetoothAdapter mBluetoothAdapter;
    private Runnable mRunnable;
    private Handler handler;
    private ScanCallback scanCallback;
    private DataTurn mDataTurn;
    private BleAdapter mBleAdapter;
    private ArrayList<BluetoothDevice> mBleList;

    /**
     * 扫描蓝牙设备
     */
    private void scanDevice() {

        mBleList.clear();
        getPopupWindow();
        popupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.pop_bottom, null,
                false), Gravity.CENTER, 0, 0);

        if (mRunnable != null)
            handler.removeCallbacks(mRunnable);

        long scanTime = 5000;
        if (isAdapterEnabled()) {
            mBluetoothAdapter.startLeScan(scanCallback);
            mRunnable = this::stopScanDevice;
            handler.postDelayed(mRunnable, scanTime);
        } else {
            mBluetoothAdapter.enable();
            handler.postDelayed(this::scanDevice, scanTime);
        }
    }

    private PopupWindow popupWindow;

    /***
     * 获取PopupWindow实例
     */
    private void getPopupWindow() {
        if (null != popupWindow) {
            popupWindow.dismiss();
        }else {
            initPopuptWindow();
        }
    }

    /**
     * 创建PopupWindow
     */
    protected void initPopuptWindow() {

        // 获取自定义布局文件pop.xml的视图
        View popupWindowView = getLayoutInflater().inflate(R.layout.pop_bottom, null,
                false);
        // 创建PopupWindow实例,2/3屏幕宽度和全屏幕高度
        RecyclerView mRecyclerView = popupWindowView.findViewById(R.id.recycler_view);
        mRecyclerView.setAdapter(mBleAdapter);

        popupWindow = new PopupWindow(popupWindowView, 2 * width / 3, height / 2, true);
        // 设置动画效果
        popupWindow.setAnimationStyle(R.style.AnimationUpDown);
        popupWindow.setOutsideTouchable(true);
        //点击其他地方消失
        popupWindow.setFocusable(true);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isFlag=true;
                invalidateOptionsMenu();
            }
        });
    }

    /**
     * 停止扫描
     */
    private void stopScanDevice() {
        if (mRunnable != null)
            handler.removeCallbacks(mRunnable);
        mBluetoothAdapter.stopLeScan(scanCallback);

    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int value = msg.what;
            if (value == 12){
                String s1 = "AA" +
                        mDataTurn.IntToHex(Integer.parseInt(edit1.getText().toString())) +
                        mDataTurn.IntToHex(Integer.parseInt(edit2.getText().toString())) +
                        mDataTurn.IntToHex(Integer.parseInt(edit3.getText().toString())) +
                        mDataTurn.IntToHex(Integer.parseInt(edit4.getText().toString())) +
                        mDataTurn.IntToHex(Integer.parseInt(edit5.getText().toString())) +
                        mDataTurn.IntToHex(Integer.parseInt(edit6.getText().toString())) +
                        mDataTurn.IntToHex(Integer.parseInt(edit7.getText().toString())) +
                        mDataTurn.IntToHex(Integer.parseInt(edit8.getText().toString())) +
                        mDataTurn.IntToHex(Integer.parseInt(edit9.getText().toString())) +
                        mDataTurn.IntToHex(Integer.parseInt(edit10.getText().toString()));
                //对前11位进行校验和处理
//            String result = s1 + mDataTurn.makeChecksum(s1);
                //对前11位进行异或处理
                String hex = mDataTurn.xorStringsHex(s1);
                String result = s1 + hex;
                //往蓝牙写入数据
                write(result);
            }

        }
    };

    /**
     * 往蓝牙写入数据方法
     */
    private void write(String info) {
        Log.i("handleMessage", "send hex data--->" + info);
        Object item = spinner.getSelectedItem();
        BTGattCallback.getInstance(this).write(gattHashMap.get(item), writeHashMap.get(item), mDataTurn.HexToByteArr(info));
    }

    @Override
    public void foundDevice(BluetoothDevice bluetoothDevice) {
        BluetoothGatt bluetoothGatt;
        for (int i=0;i<spinnerArr.size();i++){
            bluetoothGatt = gattHashMap.get(spinnerArr.get(i));
            if(bluetoothDevice.equals(bluetoothGatt.getDevice())){
                return;
            }
        }

        mBleList.add(bluetoothDevice);
        mBleAdapter.notifyDataSetChanged();
    }

    @Override
    public void connect(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        BluetoothGatt bluetoothGatt;
        boolean have = false;
        for (int i=0;i<spinnerArr.size();i++){
            bluetoothGatt = gattHashMap.get(spinnerArr.get(i));
            if (bluetoothGatt.equals(gatt)){
                have = true;
                break;
            }
        }
        if (!have){
            int j = gattHashMap.size();
            gattHashMap.put("设备"+j,gatt);
            writeHashMap.put("设备"+j,characteristic);
            isConnectMap.put("设备"+j,true);
        }

        runOnUiThread(() -> {

            WeiboDialogUtils.closeDialog(dialog);

            spinnerArr.clear();
            for (int i = 0; i < gattHashMap.size(); i++) {
                spinnerArr.add("设备" + i);
                spinnerAdapter.notifyDataSetChanged();

            }
            scrollView.setVisibility(View.VISIBLE);
            empty.setVisibility(View.GONE);
        });



    }

    @Override
    public void disConnect(BluetoothGatt gatt) {

        runOnUiThread(() -> {

            for (int i = 0; i < gattHashMap.size(); i++){
                if (gattHashMap.get("设备"+i).equals(gatt)){
                    isConnectMap.put("设备"+i,false);
                    if (spinner.getSelectedItem().toString().equals("设备"+i)){
                        isAuto = true;
                        onOff.setChecked(false);
                        isAuto = false;
                    }
                    Toast.makeText(getApplicationContext(), "设备"+i + " Bluetooth disconnect",Toast.LENGTH_SHORT).show();
                    break;
                }
            }


        });
    }



    @Override
    protected void onDestroy() {

        if (mRunnable != null) {
            mHandler.removeCallbacks(mRunnable);
        }

        for (String item : spinnerArr){
            SharedPreferencesUtil.getInstance().putValue(item, "");
        }
        super.onDestroy();
    }

}